package com.ljc.cjgl.controller;

import java.util.HashSet;
import java.util.List;

import org.abyss.data.specifications.Rule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ljc.cjgl.custom.TablePageable;
import com.ljc.cjgl.custom.TableResult;
import com.ljc.cjgl.entitiy.Course;
import com.ljc.cjgl.form.CourseForm;
import com.ljc.cjgl.service.CourseService;

@Controller
@RequestMapping(value="/course")
public class CourseController {
	@Autowired
	private CourseService service;
	
	private Specification<Course> buildSpec(CourseForm form){
		HashSet<Rule> rules=new HashSet<>();
		String search = form.getSearch();
		if(StringUtils.hasText(search)) {
			rules.add(Rule.property("name").contain(search));
		}
		return Rule.and(rules).toSpecification();
	}
	
	@RequestMapping(value="/manage")
	public String manage() {
		return "course/manage";
	}
	
	@RequestMapping(value="/page")
	@ResponseBody
	public Object page(TablePageable pageable,CourseForm form) {
		PageRequest pageRequest = pageable.bulidPageRequest();
		Specification<Course> specification = buildSpec(form);
		Page<Course> page= service.findAll(specification,pageRequest);
		return TableResult.bulidPageResult(page);
	}
	
	@RequestMapping("/edit")
	public String edit(Integer id ,ModelMap map) {
		Course model=new Course();
		if(id!=null) {
			model=service.findById(id);
		}
		map.put("model", model);
		return "course/edit";
	}
	
	@RequestMapping(value="/save")
	@ResponseBody
	public Object save(CourseForm form) {
		if(service.save(form)) {
			return TableResult.bulidResult(true, "数据保存成功");
		}else {
			return TableResult.bulidResult(false, "数据保存失败");
		}
	}
	
	
	@RequestMapping(value="/delete")
	@ResponseBody
	public Object delete(@RequestBody List<Course> courses) {
		if(service.delete(courses)) {
			return TableResult.bulidResult(true, "数据删除成功");
		}else {
			return TableResult.bulidResult(false, "数据删除失败");
		}
	}
}
